package com.waylau.spring.boot.blog.controller;

import java.util.*;

import com.waylau.spring.boot.blog.domain.Catalog;
import com.waylau.spring.boot.blog.domain.Forget;
import com.waylau.spring.boot.blog.service.CatalogService;
import com.waylau.spring.boot.blog.service.ForgetService;
import com.waylau.spring.boot.blog.util.MailUtil;
import com.waylau.spring.boot.blog.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.waylau.spring.boot.blog.domain.Authority;
import com.waylau.spring.boot.blog.domain.User;
import com.waylau.spring.boot.blog.service.AuthorityService;
import com.waylau.spring.boot.blog.service.UserService;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.ConstraintDeclarationException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 主页控制器.
 * 
 * @since 1.0.0 2017年3月8日
 * @author <a href="https://waylau.com">Way Lau</a> 
 */
@Controller
public class MainController {
	
	private static final Long ROLE_USER_AUTHORITY_ID = 2L;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private AuthorityService  authorityService;

	@Autowired
	private ForgetService forgetService;

	@Autowired
	private CatalogService catalogService;

	@Autowired
	private MailUtil mailUtil;

	@GetMapping("/")
	public String root() {
		return "redirect:/index";
	}
	
	@GetMapping("/index")
	public String index() {
		return "redirect:/blogs";
	}

	/**
	 * 获取登录界面
	 * @return
	 */
	@GetMapping("/login")
	public String login() {
		return "login";
	}

	/**
	 * 获取忘记密码界面
	 * @return
	 */
	@GetMapping("/forgetPwd")
	public String forgetPwd() {
		return "forgetPwd";
	}

	@GetMapping("/login-error")
	public String loginError(Model model) {
		model.addAttribute("loginError", true);
		model.addAttribute("errorMsg", "登陆失败，账号或者密码错误！");
		return "login";
	}
	
	@GetMapping("/register")
	public String register() {
		return "register";
	}
	
	/**
	 * 注册用户
	 * @return
	 */
	@GetMapping("/toRegister")
	public ResponseEntity<Response> registerUser(
			@RequestParam(value="username") String username,
			@RequestParam(value="email") String email,
			@RequestParam(value="name") String name,
			@RequestParam(value="password") String password) {

		User user = new User(name,email,username,password);

		List<Authority> authorities = new ArrayList<>();
		authorities.add(authorityService.getAuthorityById(ROLE_USER_AUTHORITY_ID));
		user.setAuthorities(authorities);
		try{
			user = userService.saveUser(user);
			Catalog catalog = new Catalog();
			catalog.setName("随记");
			catalog.setUser(user);
			catalogService.saveCatalog(catalog);
			return ResponseEntity.ok(new Response(true,""));
		}catch (ConstraintViolationException cve){
			String errMsg = "";
			for (ConstraintViolation<?> a : cve.getConstraintViolations()) {
				errMsg+=a.getMessage()+";";
			}
			return ResponseEntity.ok(new Response(false,errMsg));
		}
	}
	
	@GetMapping("/search")
	public String search() {
		return "search";
	}

	@GetMapping("/forget/{uuid}")
	public ModelAndView toUpdatePwd(@PathVariable("uuid") String uuid,Model model){
		Forget forget = forgetService.findById(uuid);
		//无效
		if(forget==null||forget.getStatus()==1||forget.getTime().getTime()-System.currentTimeMillis()>24*60*60*1000){
			model.addAttribute("message","连接已失效");
			model.addAttribute("url","/login");
			return new ModelAndView("jump","modal",model);
		}
		model.addAttribute("username",forget.getCode());
		model.addAttribute("id",forget.getId());
		return new ModelAndView("updatePwd","userModal",model);
	}

	@PostMapping("/updatePwd")
	public ModelAndView toUpdatePwd(User user,Model model){
		User u = userService.getUserByUsername(user.getUsername());
		u.setPassword(user.getPassword());
		userService.updateUser(u);
		forgetService.updateStatus(user.getUsername(),1);

		model.addAttribute("message","修改密码成功");
		model.addAttribute("url","/login");
		return new ModelAndView("jump","modal",model);
	}

	@GetMapping("/sendUpdatePasswordEmail")
	public ResponseEntity<Response> sendUpdatePasswordEmail(@RequestParam(value="userName") String userName,
															@RequestParam(value="email") String email){
		User user = userService.checkUserByUserNameAndEmail(userName, email);
		if(user!=null){
			//发送人邮箱
			String deliver = "784128953@qq.com";
			//接收人邮箱,这是一个数组
			String[] receiver = {user.getEmail()};
			//抄送者邮件地址,这是一个数组
			String[] carbonCopy = {};
			String uuid = UUID.randomUUID().toString().replaceAll("-","");
			String subject = "渔歌,密码找回服务";
			String content = "点击下面链接找回密码<a href='http://localhost:1112/forget/"+uuid+"'>"+uuid+"</a>";

			boolean isHtml = true;

			try {
				mailUtil.sendHtmlEmail(deliver, receiver, carbonCopy, subject, content, isHtml);
				forgetService.insert(uuid,userName);
				return ResponseEntity.ok().body(new Response(true,"邮件发送成功"));
			} catch (Exception e) {
				e.printStackTrace();
				return ResponseEntity.ok().body(new Response(false,"邮件发送失败"));
			}
		}else{
			return ResponseEntity.ok().body(new Response(false,"账户邮箱不匹配"));
		}
	}
}
